package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 先获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 从request中获取请求的参数
        MultiValueMap<String, String> valueMap = request.getQueryParams();
        String authorization = valueMap.getFirst("authorization");
        //3. 判断参数是否为admin如果是则放行
         if ("admin".equals(authorization)){
             return chain.filter(exchange);
         }
         response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //4. 如果不是admin则返回401的状态并结束请求
        return response.setComplete() ;
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
